<?php
/**
 * Created by DRCOM.
 * User: GZX
 * Datetime: 2022-01-24 15:27
 */
//define('VER', '1.0.3');
//define('ENV', 'cloud1-5gr8au5vfcc1e784');
//define('TABLE', 'test1');//设备编号
//define('RADIUS_IP', '192.168.4.243');//RADIUS地址
//define('ACCOUNT', 'common');//临时账号
//define('PASSWORD', '123456');//临时账号密码
//define('SUFFIX', '');//账号后缀
//define('CRC_KEY', 'drcom.com');
//define('TOKEN_FILE', '/dev/shm/minitoken');

define('VER', '1.0.3');
define('ENV', 'cloud1-5gr8au5vfcc1e784');
define('TABLE', 'VM22NM1001');//设备编号
define('RADIUS_IP', '192.168.34.107');//RADIUS地址
define('ACCOUNT', 'guest@9000');//临时账号
define('PASSWORD', '123456');//临时账号密码
define('SUFFIX', '@1001');//账号后缀
define('CRC_KEY', 'drcom.com');
define('TOKEN_FILE', '/dev/shm/aaa');

$APPID = 'wxa97c07295350189b';
$APPSECRET = '43c5188627bfe6a20da906fa528b3aad';
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$APPID&secret=$APPSECRET";
$contents = file_get_contents($url);

var_dump($APPID);
var_dump($contents);
exit;
if (PHP_SAPI == 'cli') $_GET['action'] = 'task';
switch ($_GET['action']) {
    case 'version':
        echo VER;
        break;
    case 'token':
        echo get_token();
        break;
    case 'scheme':
        $scheme = get_scheme();
        echo $scheme;
        break;
    case 'guest':
        $guest = get_guest();
        if (!empty($guest)) {
            echo 'guest:' . count($guest) . '<br>';
            var_dump($guest);
        }


        break;
    case 'task':
        do {
            echo date('Y-m-d H:i:s');
            echo PHP_EOL;
            $guest = get_guest();
            if (!empty($guest)) {
                $access_token = get_token();
                $query = 'db.collection("' . TABLE . '").limit(10).get()';
                $result = getwxfetch($query, $access_token);
                echo $result;
                echo PHP_EOL;
                $data = json_decode($result, true);
                if (isset($data['data'])) {
                    foreach ($data['data'] as $row) {
                        echo $row;
                        echo PHP_EOL;
                        $row = json_decode($row, true);
                        echo $row['phone'] . PHP_EOL;
                        echo $row['ip'] . PHP_EOL;
                        unset($guest[$row['ip']]);
                        echo 'drcom_login:' . drcom_login($row['phone'], $row['ip']);
                        echo PHP_EOL;
                        $query = 'db.collection("' . TABLE . '").doc("' . $row['_id'] . '").remove()';
                        echo getwxdelete($query, $access_token);
                        echo PHP_EOL;
                    }
                } else {
                    echo $result;
                    echo PHP_EOL;
                }

            }
            sleep(10);
        } while (true);
        break;
    default:
        $output = get_scheme();
        $result = json_decode($output, true);
        if ($result['errcode'] == 0) {
            $scheme = $result['openlink'];
            $html = <<<HTML
	<!DOCTYPE html>
	<html>
	<head> 
	<meta charset="utf-8">  
	<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=0"> 
	<meta name="apple-mobile-web-app-capable" content="yes"> 
	<meta name="apple-mobile-web-app-status-bar-style" content="black">
	<meta name="format-detection" content="telephone=no"> 
	<title>跳转中...</title>
	</head>
	<body> 
	<div style="display:none;"><iframe width=0 height=0 src="$login"></iframe></div>
	<div style="text-align: center;font-size: 18px;margin: 100px 0 30px 0;">正在前往微信客户端</div> 
	<a target="_self" id="wx" href="$scheme" style="width: 90%;background: #1AAD19;text-align: center;color: #fff;margin: 0 auto;box-sizing: border-box;font-size: 18px;line-height: 2.55555556;border-radius: 5px;display: block;text-decoration: none;">打开微信</a> 
	<script>
	    var aObj = document.getElementById("wx");
        var ua = navigator.userAgent;
        if (ua.indexOf("iPhone") != -1 || ua.indexOf("iPod") != -1 || ua.indexOf("iPad") != -1) {
            aObj.target = "_system";
        }else{
            aObj.target = "_system";
            aObj.innerText = "重新跳转";
            window.location.href="$scheme";
        }
	     
	</script>
	</body>
	</html>
HTML;
            echo $html;
        }
}


function post_curls($url, $post)
{
    $curl = curl_init(); // 启动一个CURL会话
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
    curl_setopt($curl, CURLOPT_TIMEOUT, 30);
    curl_setopt($curl, CURLOPT_HEADER, 0);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $res = curl_exec($curl); // 执行操作
    if (curl_errno($curl)) {
        echo 'Errno' . curl_error($curl);//捕抓异常
    }
    curl_close($curl); // 关闭CURL会话
    return $res; // 返回数据，json格式

}

//获取微信小程序的token
function get_token()
{
    if (file_exists(TOKEN_FILE) && filemtime(TOKEN_FILE) > strtotime("-1 hour")) {
        $contents = file_get_contents(TOKEN_FILE);
    } else {
        $APPID = 'wxa97c07295350189b';
        $APPSECRET = '43c5188627bfe6a20da906fa528b3aad';
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$APPID&secret=$APPSECRET";
        $contents = file_get_contents($url);

        file_put_contents(TOKEN_FILE, $contents);
    }

    $data = json_decode($contents, true);
    return $data['access_token'];
}


//数据更新
function getwxupdate($query, $accesstoken)
{
    global $env;
    $data['env'] = $env;
    $data['query'] = $query;
    $body = json_encode($data);
    $info = post_curls("https://api.weixin.qq.com/tcb/databaseupdate?access_token=$accesstoken", $body);
    return $info;
}

//数据插入
function getwxinsert($query, $accesstoken)
{

    $data['env'] = ENV;
    $data['query'] = $query;
    $body = json_encode($data);
    $info = post_curls("https://api.weixin.qq.com/tcb/databaseadd?access_token=$accesstoken", $body);
    return $info;
}

//数据取用
function getwxfetch($query, $accesstoken)
{
    $data['env'] = ENV;
    $data['query'] = $query;
    $body = json_encode($data);
    $info = post_curls("https://api.weixin.qq.com/tcb/databasequery?access_token=$accesstoken", $body);
    return $info;
}

//数据删除
function getwxdelete($query, $accesstoken)
{
    $data['env'] = ENV;
    $data['query'] = $query;
    $body = json_encode($data);
    $info = post_curls("https://api.weixin.qq.com/tcb/databasedelete?access_token=$accesstoken", $body);
    return $info;
}

//drcom认证
function drcom_login($account, $ip)
{
    $arrip = explode(".", $ip);
    $session_id = bin2hex(chr($arrip[0])) . bin2hex(chr($arrip[1])) . bin2hex(chr($arrip[2])) . bin2hex(chr($arrip[3])) . "-000000000000-0000";
    $password = str_pad(dechex(crc32($account . SUFFIX . CRC_KEY)), 8, '0', STR_PAD_LEFT);
    echo $password . PHP_EOL;
//    $logout = @dren_portal(0, 1, RADIUS_IP, 1812, 1, 0, '123', ACCOUNT, PASSWORD, $session_id);
//    echo 'logout:' . ACCOUNT . "\t" . PASSWORD . "\t" . $logout . PHP_EOL;
    $result = @dren_portal(0, 0, RADIUS_IP, 1812, 1, 0, '123', $account . SUFFIX, $password, $session_id);
    return $result;
}

//打开微信小程序
function get_scheme()
{
    $table = TABLE;
    $ip = $_SERVER['REMOTE_ADDR'];
    $token = get_token();
    $url = "https://api.weixin.qq.com/wxa/generatescheme?access_token=$token";
    $data['jump_wxa'] = ['path' => '/pages/portal/index', 'query' => "table=$table&ip=$ip"];
    $data['is_expire'] = true;
    $data['expire_type'] = 1;
    $data['expire_interval'] = 1;
    $body = json_encode($data);
    $info = post_curls($url, $body);
    return $info;
}

//监控是否有临时账号在线
function get_guest()
{
    $R3503 = dren_SendCommandEx('G3503');;
    $file = substr($R3503, -18);
    $contents = file_get_contents($file);
    $list = explode("R3503", trim($contents));
    $guest = [];
    foreach ($list as $row) {
        $row = trim($row);
        $line = explode("\t", $row);
        if ($line[0] == ACCOUNT) {
            $guest[$line[2]] = $line;
        }

    }
    return $guest;
}

